package com.mhc.suzuki.service.impl;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.CreditQueryApplyBO;
import com.mhc.suzuki.bo.SubmitTaskBO;
import com.mhc.suzuki.constant.*;
import com.mhc.suzuki.dal.model.*;
import com.mhc.suzuki.dal.query.*;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.manager.*;
import com.mhc.suzuki.service.ModifyService;
import com.mhc.suzuki.service.OrderAuditApplyService;
import com.mhc.suzuki.service.OrderAuditTaskService;
import com.mhc.suzuki.util.BeanCopierUtil;
import com.mhc.suzuki.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HMJ on 2017/8/24.
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderAuditApplyServiceImpl implements OrderAuditApplyService {

    @Autowired
    private OrderAuditApplyManager orderAuditApplyManager;

    @Autowired
    private OrderAuditTaskService orderAuditTaskService;

    @Autowired
    private ModifyService modifyService;
    @Autowired
    private CarInfoManager carInfoManager;
    @Autowired
    private LoanInfoManager loanInfoManager;
    @Autowired
    private OrderManager orderManager;
    @Autowired
    private CreditQueryApplyManager creditQueryApplyManager;
    /**
     * 创建申请记录
     *
     * @param submitTaskBO 申请内容
     * @param logedUser    登录信息
     * @return
     * @throws Exception
     */
    @Override
    public Long addOrderAuditApply(SubmitTaskBO submitTaskBO, User logedUser) throws SuzukiCommonException {
        log.info("开始插入申请记录");
        OrderAuditApplyDO record = new OrderAuditApplyDO();
        BeanUtils.copyProperties(submitTaskBO, record);
        record.setStaffName(logedUser.getStaffName());      //业务员名称
        record.setStaffId(logedUser.getStaffId());          //发起申请的员工ID
        record.setOrderNo(submitTaskBO.getOrderNo());   //订单号
        record.setApplyType(submitTaskBO.getApplyType());  //申请业务类型
        record.setRemark(submitTaskBO.getRemark());      //申请备注
        long count = orderAuditApplyManager.insertSelective(record);
        if (count > 0) {
            log.info("插入申请记录成功，申请编号：{}", record.getApplyId());
            return record.getApplyId();
        }
        throw new SuzukiCommonException(ErrorCodeEnum.GETDATA_ERROR);
    }

    @Override
    public List<OrderAuditApplyVO> queryOrderAuditApplyList(String orderNO, Integer applyType, Integer approvalResult,String roleCode) {
        OrderAuditApplyQuery query = new OrderAuditApplyQuery();
        query.createCriteria().andOrderNoEqualTo(orderNO).andApplyTypeEqualTo(applyType);
        //查询的审核记录
        List<OrderAuditApplyDO> orderAuditApplyDOList = orderAuditApplyManager.selectByQuery(query);
        List<OrderAuditApplyVO> orderAuditApplyVOList = new ArrayList<>();
        orderAuditApplyDOList.forEach(orderAuditApplyDO -> {
            OrderAuditApplyVO orderAuditApplyVO = BeanCopierUtil.convert(orderAuditApplyDO, OrderAuditApplyVO.class);
            //审核节点人员记录
            if (ApplyTypeEnum.MODIFY_APPLY.getCode().equals(orderAuditApplyDO.getApplyType())) {
                List<ModifyHisVO> modifyHisVOList = modifyService.queryModifyRecordList(orderNO, EntityTypeEnum.ORDER.getCode());
                //资料修改记录
                orderAuditApplyVO.setModifyHisVOList(modifyHisVOList);
            } else {
                List<OrderAuditTaskVO> orderAuditTaskVOList = orderAuditTaskService.queryOrderAuditTaskList(orderNO, applyType, approvalResult, orderAuditApplyDO.getApplyId(),roleCode);

                //审核记录
                orderAuditApplyVO.setOrderAuditTaskList(orderAuditTaskVOList);
            }
            orderAuditApplyVOList.add(orderAuditApplyVO);

        });

        return orderAuditApplyVOList;
    }


    @Override
    public ModifyInfoVO queryApplyInfo(String orderNO, Integer applyCode) {
        ModifyInfoVO modifyInfoVO = new ModifyInfoVO();
        OrderAuditApplyQuery query = new OrderAuditApplyQuery();
        query.setOrderByClause("gmt_create desc");
        query.createCriteria().andOrderNoEqualTo(orderNO).andApplyTypeEqualTo(applyCode);
        //查询的审核记录
        List<OrderAuditApplyDO> orderAuditApplyDOList = orderAuditApplyManager.selectByQuery(query);
        if (!CollectionUtils.isEmpty(orderAuditApplyDOList)) {
            OrderAuditApplyDO orderAuditApplyDO = orderAuditApplyDOList.get(0);
            modifyInfoVO = BeanCopierUtil.convert(orderAuditApplyDO, ModifyInfoVO.class);
            modifyInfoVO.setOrderNo(orderNO);
            modifyInfoVO.setRemark(orderAuditApplyDO.getRemark());
            modifyInfoVO.setModifyStaffName(orderAuditApplyDO.getStaffName());
            modifyInfoVO.setModifyCreate(orderAuditApplyDO.getGmtCreate());
            CarInfoQuery carInfoQuery = new CarInfoQuery();
            carInfoQuery.createCriteria().andOrderNoEqualTo(orderNO);
            List<CarInfoDO> carInfoDOS = carInfoManager.selectByQuery(carInfoQuery);
            if (!CollectionUtils.isEmpty(carInfoDOS)) {
                modifyInfoVO.setCarModel(carInfoDOS.get(0).getCarModel());
            }
            OrderQuery orderQuery = new OrderQuery();
            Integer orderStatus = OrderStatusEnum.CANCELLED.getCode();//订单状态设置
            orderQuery.createCriteria().andOrderNoEqualTo(orderNO)
                    .andOrderStatusNotEqualTo(orderStatus);//订单状态设置，不为作废
            List<OrderDO> orderDOS = orderManager.selectByQuery(orderQuery);
            OrderDO orderDO;
            if(!CollectionUtils.isEmpty(orderDOS)){
                orderDO = orderDOS.get(0);
                modifyInfoVO.setDeptName(orderDO.getDeptName());
                modifyInfoVO.setCustomerName(orderDO.getCustomerName());
                modifyInfoVO.setStaffName(orderDO.getStaffName());
                modifyInfoVO.setApplyCreate(orderDO.getGmtCreate());
            }

            LoanInfoQuery loanInfoQuery = new LoanInfoQuery();
            loanInfoQuery.createCriteria().andOrderNoEqualTo(orderNO).andIsDeletedEqualTo(IsDeletedEnum.NORMAL.getCode());
            List<LoanInfoDO> loanInfoDOList = loanInfoManager.selectByQuery(loanInfoQuery);
            if (!CollectionUtils.isEmpty(loanInfoDOList)) {
                modifyInfoVO.setLoanAmount(loanInfoDOList.get(0).getLoanAmount());
            }
        }

        if(ApplyTypeEnum.MODIFY_APPLY.getCode().equals(applyCode)){
            //资料修改记录
            List<ModifyHisVO> modifyHisVOList = modifyService.queryModifyRecordList(orderNO, EntityTypeEnum.ORDER.getCode());
            modifyInfoVO.setModifyHisVOList(modifyHisVOList);
        }

        List<CreditQueryApplyBO> creditInfoList = creditQueryApplyManager.selectByCreditInfo(orderNO);
        for(CreditQueryApplyBO creditQueryApplyBO : creditInfoList) {
            //婚姻状态
            if (AnnexGroupEnum.BUYER.getCode().toString().equals(creditQueryApplyBO.getCustomerType())) {
                modifyInfoVO.setBemarried(creditQueryApplyBO.getBemarried());
            }
            //是否有担保人
            if (AnnexGroupEnum.SPONSOR.getCode().toString().equals(creditQueryApplyBO.getCustomerType())) {
                modifyInfoVO.setSponsor(Boolean.TRUE);
            }
        }

        return modifyInfoVO;
    }
}
